using System;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using Voodoo.Sauce.Internal;

namespace Voodoo.Sauce.Debugger
{
	public class LogsOptionDebugScreen : Screen
	{
		[SerializeField]
		private Toggle enableDebugLogsToggle;

		[SerializeField]
		private GameObject restartLogsView;

		[SerializeField]
		private RectTransform logFilterContainer;

		[SerializeField]
		private GameObject logFilterParent;

		[Header("Prefabs")]
		[SerializeField]
		private Toggle logFilterPrefab;

		[SerializeField]
		private Text logHeaderTextPrefab;

		private bool _originalDebugLogsEnabled;

		private Toggle[] _logFilterToggles;

		private void Awake()
		{
			enableDebugLogsToggle.onValueChanged.AddListener(OnEnableDebugLogsToggled);
			enableDebugLogsToggle.isOn = VoodooLog.IsDebugLogsEnabled;
			_originalDebugLogsEnabled = VoodooLog.IsDebugLogsEnabled;
			restartLogsView.SetActive(value: false);
		}

		private void OnDestroy()
		{
			enableDebugLogsToggle.onValueChanged.RemoveListener(OnEnableDebugLogsToggled);
		}

		private void Start()
		{
			CreateLogModuleToggles();
			UnityEngine.Object.Destroy(logHeaderTextPrefab.gameObject);
			UnityEngine.Object.Destroy(logFilterPrefab.gameObject);
		}

		private void CreateLogModuleToggles()
		{
			string[] enumValues = GetEnumValues(typeof(Module));
			UnityEngine.Object.Instantiate(logHeaderTextPrefab, logFilterContainer).text = "Log Module";
			_logFilterToggles = new Toggle[enumValues.Length - 1];
			for (int i = 1; i < enumValues.Length - 1; i++)
			{
				_logFilterToggles[i - 1] = CreateModuleToggle(i, enumValues[i]);
			}
		}

		private Toggle CreateModuleToggle(int index, string moduleName)
		{
			Toggle toggle = UnityEngine.Object.Instantiate(logFilterPrefab, logFilterContainer);
			toggle.GetComponentInChildren<Text>().text = FormatModuleName(moduleName);
			int moduleFilter = VoodooLog.ModuleFilter;
			int value = 1 << index - 1;
			toggle.isOn = (moduleFilter & value) > 0;
			toggle.onValueChanged.AddListener(delegate
			{
				OnLogModuleChanged(value);
			});
			return toggle;
		}

		private string FormatModuleName(string module)
		{
			string text = module.ToLower().Replace('_', ' ');
			return text.Substring(0, 1).ToUpper() + text.Substring(1);
		}

		private void OnLogModuleChanged(int value)
		{
			VoodooLog.ToggleModule(value);
		}

		private void OnEnableDebugLogsToggled(bool enableLogs)
		{
			VoodooLog.EnableDebugLogs(enableLogs);
			restartLogsView.SetActive(enableLogs != _originalDebugLogsEnabled);
			logFilterParent.SetActive(enableLogs);
		}

		private string[] GetEnumValues(Type enumType)
		{
			return (from o in Enum.GetValues(enumType).OfType<object>()
				select o.ToString()).ToArray();
		}
	}
}
